﻿using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;
using DataStore;
using DataStore.Domain;
using DataStore.Repositories;
using Infrastructure.CurrentData;
using Microsoft.Practices.Composite.Events;

namespace Infrastructure.ViewModels
{
    /// <summary>
    /// ViewModel for all categories
    /// </summary>
    public class AllCategoriesViewModel : DataModel
    {
        /// <summary>
        /// Categories
        /// </summary>
        ObservableCollection<CategoryViewModel> _categories = new ObservableCollection<CategoryViewModel>();

        /// <summary>
        /// Initializes a new instance of the <see cref="AllCategoriesViewModel"/> class.
        /// </summary>
        public AllCategoriesViewModel() : base()
        {
            Initialize();
        }


        /// <summary>
        /// Initializes a new instance of the <see cref="AllCategoriesViewModel"/> class.
        /// </summary>
        public AllCategoriesViewModel(IEventAggregator eventAggregator) : base(eventAggregator)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        void Initialize()
        {
            State = ModelState.Fetching;

            RefreshCategories();
        }


        /// <summary>
        /// Refreshes the categories.
        /// </summary>
        void RefreshCategories()
        {
            if (!ThreadPool.QueueUserWorkItem(new WaitCallback(FetchCategoriesCallback)))
            {
                State = ModelState.Invalid;
            }
        }

        /// <summary>
        /// Gets or sets the categories.
        /// </summary>
        /// <value>The categories.</value>
        public ObservableCollection<CategoryViewModel> Categories
        {
            get
            {
                VerifyCalledOnUIThread();
                return _categories;
            }
            set
            {
                VerifyCalledOnUIThread();
                if(_categories != value)
                {
                    _categories = value;
                    OnPropertyChanged("Categories");
                }
            }
        }

        /// <summary>
        /// Fetches the categories from data store.
        /// </summary>
        /// <param name="state">The state.</param>
        void FetchCategoriesCallback(object state)
        {
            IDatabase database = Current.Container.Resolve<IDatabase>();
            var unitOfWork = database.CreateUnitOfWork();

            try
            {
                IRepository<Category> repository = new CategoryRepository(unitOfWork);

                var categories = repository.All;

                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            Categories.Clear();
                                            foreach (var category in categories)
                                            {
                                                Categories.Add(new CategoryViewModel(EventAggregator, category));
                                            }
                                            unitOfWork.Dispose();
                                            State = ModelState.Active;
                                            OnLoaded(this, EventArgs.Empty);
                                        }),
                    DispatcherPriority.ApplicationIdle);
            }
            catch (Exception e)
            {
                Log.Error("Failed to load Categories", e);

                unitOfWork.Dispose();
                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            State = ModelState.Invalid;
                                            OnLoaded(this, EventArgs.Empty);
                                        }),
                    DispatcherPriority.ApplicationIdle);

            }
        }
    }
}